package com.rgst.controller;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.rgst.dao.entity.Busi;
import com.rgst.dao.entity.BusiConfig;
import com.rgst.dao.entity.ExtFields;
import com.rgst.dao.repository.BusiExtFieldsRepository;
import com.rgst.dao.repository.BusiRepository;
import com.rgst.dto.Result;
import com.rgst.serivce.BusiConfigService;

/**
 * Created by tancwon 2019/11/22.
 */
@Controller
@RequestMapping("busi")
public class BusiController extends BaseController {

    @Autowired
    private BusiConfigService busiConfigService;

    @Autowired
    private BusiRepository busiRepository;
    @Autowired
    private BusiExtFieldsRepository busiExtFieldsRepository;

    @RequestMapping("loadConfigByTypeAndTitle")
    @ResponseBody
    public Result<List<BusiConfig>> loadConfigByTypeAndTitle(String likeTitle, String type){
        Assert.notNull(likeTitle,"title can't be null");
        Assert.notNull(type,"type can't be null");
        List<BusiConfig> gradeList = busiConfigService.findAllGradeByTypeAndLikeTitle(type, likeTitle);
        return Result.success(gradeList);
    }

    @GetMapping("loadBusiConfig")
    public ModelAndView loadBusConfig(Long busiId) {
        ModelAndView modelAndView = new ModelAndView();

        Optional<Busi> busiRet = busiRepository.findById(busiId);
        Busi busi = null;
        if (!busiRet.isPresent() || !(busi = busiRet.get()).isValid()) {
            modelAndView.setViewName("error");
            modelAndView.addObject("message", "");
            return modelAndView;
        }
        String dep = busi.getDep();
        List<BusiConfig> gradeList = busiConfigService.findAllGradeByTypeAndLikeTitle("grade", dep);
        if(gradeList != null){
            BusiConfig grade = gradeList.get(0);
            String gradeName = grade.getValue();
            List<BusiConfig> classList = busiConfigService.findAllGradeByTypeAndLikeTitle("class", gradeName);
            modelAndView.addObject("classList", classList);
        }
        List<BusiConfig> nationList = busiConfigService.findAllByType("nation");
        List<ExtFields> extFields = busiExtFieldsRepository.findAllByBusiId(busiId);
        modelAndView.setViewName("enroll");
        modelAndView.addObject("busi", busi);
        modelAndView.addObject("gradeList", gradeList);
        modelAndView.addObject("nationList", nationList);
        modelAndView.addObject("extFields", extFields);
        return modelAndView;
    }

}
